package com.seal.commons.validator.jsr303;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import org.apache.commons.beanutils.BeanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class FieldMatchValidator implements ConstraintValidator<FieldMatch, Object> {
    
    final static Logger LOGGER = LoggerFactory.getLogger(FieldMatchValidator.class);
    
    private String firstFieldName;
    private String secondFieldName;
    private String message;
    
    @Override  
    public void initialize(FieldMatch fieldMatch) {
        this.firstFieldName = fieldMatch.first();
        this.secondFieldName = fieldMatch.second();
        this.message = fieldMatch.message();
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        boolean toReturn = false;

        try{
            final Object firstObj = BeanUtils.getProperty(value, firstFieldName );
            final Object secondObj = BeanUtils.getProperty(value, secondFieldName );

            toReturn = firstObj == null && secondObj == null || firstObj != null && firstObj.equals(secondObj);
        }
        catch (final Exception e){
            LOGGER.error("first:["+firstFieldName+"],secondFieldName:["+secondFieldName+"]",e);
        }
        if(!toReturn) {
            context.disableDefaultConstraintViolation();
            context.buildConstraintViolationWithTemplate(message).addPropertyNode(firstFieldName).addPropertyNode(secondFieldName);
        }
        return toReturn;
    }  

}  
